package com.wl.controller;

import com.mysql.cj.util.StringUtils;
import com.wl.constant.Constant;
import com.wl.mapper.ArticlesMapper;
import com.wl.pojo.Articles;
import com.wl.response.CommonReturnType;
import com.wl.service.impl.ArticlesServiceImpl;
import com.wl.util.*;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: treeHole
 * @author: 吴磊
 * @create: 2021-07-25 00:45
 */
@WebServlet("/jsoup.action")
public class JsoupServlet extends BaseServlet {
    private ArticlesMapper articlesMapper = MybatisUtils.getMapper(ArticlesMapper.class);
    private ArticlesServiceImpl articlesService = new ArticlesServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getParameter("op");
        if (StringUtils.isNullOrEmpty(op)) {
            show404Common(request, response);
            return;
        }
        if ("getArticleByURL".equals(op)) {
            getArticleByURLOp(request, response);
        } else if ("getArticleByURLAuto".equals(op)) {
            getArticleByURLAutoOp(request, response);
        } else {
            show404Common(request, response);
        }
    }

    /**
     * 根据输入地址的起始范围和结束范围爬取文章
     *
     * @param request
     * @param response
     */
    private void getArticleByURLAutoOp(HttpServletRequest request, HttpServletResponse response) {
        int i = new JsoupUtil().getArticleByURLAuto(request);
        MyUtil.responseData(response, CommonReturnType.success(i));
    }

    /**
     * 爬取数据并插入到数据库
     *
     * @param request
     * @param response
     */
    private void getArticleByURLOp(HttpServletRequest request, HttpServletResponse response) {

        String userId = request.getParameter("userId");
        if (userId == null) {
            userId = TokenUtils.getUser(request).getUserId();
        }
        Jedis jedis = RedisUtil.getJedis();
        String url = request.getParameter("url");
        if (jedis.sismember(Constant.JSOUP_URL, url.trim())) {
            MyUtil.responseData(response, CommonReturnType.fail(null));
            return;
        } else {
            jedis.sadd(Constant.JSOUP_URL, url.trim());
        }
        List<Map<String, Object>> maps = JsoupUtil.getArticleByURL(url);

        String finalUserId = userId;
        maps.forEach(map -> {
            String articleContent = (String) map.get("html");
            ArrayList<String> tags = (ArrayList<String>) map.get("tags");
            String articleLabel = (String) map.get("strTag");
            articleLabel = articleLabel == null ? "" : articleLabel;
            Articles articles = new Articles();
            String articleId = MyUtil.getUUID();
            articles.setArticleId(articleId);
            articles.setArticleStatus("1");
            articles.setArticleDate(MyUtil.getCurrentDetailedTime());
            articles.setUserId(finalUserId);
            articles.setArticleLabel(articleLabel);
            articles.setArticleContent(articleContent);
            Integer i = articlesMapper.insertByJsoup(articles);
            if (i > 0) {
                jedis.zadd(Constant.INTEGRAL, 0, articleId);
                if (tags != null && tags.size() > 0) {
                    tags.forEach(label -> {
                        jedis.sadd(label, articleId);
                        jedis.sadd(Constant.ALL_LABELS, label);
                    });
                }
            }
            articlesService.createIndex(articles);
        });
        jedis.close();
        MyUtil.responseData(response, CommonReturnType.success(maps.size()));
    }
}
